﻿using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using UnityEngine.UI;

public class CreateObjects : MonoBehaviour {

	static List<Sprite> stickersList;

	[MenuItem ("TOOLS/Create Objects in Fidget Shop")]
	static void RefreshMyDiary()
	{
		if(EditorApplication.currentScene.Equals("Assets/Scenes/GamePlay.unity") || EditorApplication.currentScene.Equals("Assets/Scenes/MainScene.unity"))
		{
			Debug.Log("TO BRE");
			if(GameObject.Find("Canvas") != null)
			{
				DirectoryInfo dirInfo = new DirectoryInfo("Assets/Resources/Textures/Content");
				FileInfo[] fileInfo = dirInfo.GetFiles("*.png");
				int stickersCount = fileInfo.Length;

				stickersList = new List<Sprite>();

				for(int i=0;i<stickersCount;i++)
				{
					Sprite[] stickers = Resources.LoadAll<Sprite>("Textures/Content/SpinnersTexture" + (i+1).ToString());
					Debug.Log("stickers: " + stickers.Length);
					for(int j=0;j<stickers.Length;j++)
					{
						stickersList.Add(stickers[j]);
					}
				}

				GameObject canvas = GameObject.Find("Canvas");
				Transform content = canvas.transform.Find("PopUps/PopUpShop/AnimationHolder/Body/ContentHolder/ScrollRect/ScrollObjectHolder");
				GameObject item = content.Find("Item1").gameObject;

				if(content.childCount > 1)
				{
					GameObject[] objectsToDestroy = new GameObject[content.childCount-1];
					//deleting previous existing objects
					for(int i=0;i<content.childCount;i++)
					{
						if(i>0)
							objectsToDestroy[i-1] = content.GetChild(i).gameObject;
					}
					for(int i=0;i<objectsToDestroy.Length;i++)
						DestroyImmediate(objectsToDestroy[i]);
				}
				item.transform.GetChild(0).GetComponent<Image>().sprite = null;

				GameObject newItem = content.GetChild(0).gameObject;
				//adding new objects
				for(int i=0;i<stickersList.Count;i++)
				{
					if(i>0)
					{
						newItem = Instantiate(item) as GameObject;
						newItem.name = "Item"+(i+1);
						newItem.transform.SetParent(item.transform.parent);
						newItem.transform.localPosition = new Vector3(newItem.transform.localPosition.x,newItem.transform.localPosition.y,0);
						newItem.transform.localScale = Vector3.one;
					}

					newItem.transform.GetChild(0).GetComponent<Image>().sprite = stickersList[i];
				}

				EditorUtility.DisplayDialog("SUCCESS - Objects created in Shop","Find 'PopupUpShop' gameObject and press 'Apply' to save changes in prefab.","OK");
			}
			else
			{
				EditorUtility.DisplayDialog("Creating Objects Failed","There is no gameObject named 'Canvas' in this scene.","OK");
				Debug.Log("NEMA OBJEKTA SA Canvas TAGOM");
			}
		}
		else
		{
			EditorUtility.DisplayDialog("Creating Objects Failed","You must be either in scene 'GamePlay' or 'MainScene' in order to create objects.","OK");
			Debug.Log("NIJE TA SCENA");
		}
	}		
}
